<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="这一节解析一下 java NIO中 ServerSocketChannel创建的过程 channel  在java中表示通道，是用来进行数据的有效传输  广义上来说通道可以被分为两类：File I/O和Stream I/O，也就是文件通道和套接字通道 如果分的更细致一点则是：  FileChannel 从文件读写数据 SocketChannel 通过TCP读写网络数据 ServerSocketCh">
<meta property="og:type" content="article">
<meta property="og:title" content="kyssion-blog">
<meta property="og:url" content="http://yoursite.com/2018/10/09/java-从源代码分析javaNIO的运行过程(一)/index.html">
<meta property="og:site_name" content="kyssion-blog">
<meta property="og:description" content="这一节解析一下 java NIO中 ServerSocketChannel创建的过程 channel  在java中表示通道，是用来进行数据的有效传输  广义上来说通道可以被分为两类：File I/O和Stream I/O，也就是文件通道和套接字通道 如果分的更细致一点则是：  FileChannel 从文件读写数据 SocketChannel 通过TCP读写网络数据 ServerSocketCh">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://yoursite.com/blogimg/nio/1.png">
<meta property="og:updated_time" content="2018-10-09T07:22:37.337Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="kyssion-blog">
<meta name="twitter:description" content="这一节解析一下 java NIO中 ServerSocketChannel创建的过程 channel  在java中表示通道，是用来进行数据的有效传输  广义上来说通道可以被分为两类：File I/O和Stream I/O，也就是文件通道和套接字通道 如果分的更细致一点则是：  FileChannel 从文件读写数据 SocketChannel 通过TCP读写网络数据 ServerSocketCh">
<meta name="twitter:image" content="http://yoursite.com/blogimg/nio/1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/10/09/java-从源代码分析javaNIO的运行过程(一)/"/>





  <title> | kyssion-blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">kyssion-blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-schedule">
          <a href="/schedule/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-calendar"></i> <br />
            
            日程表
          </a>
        </li>
      
        
        <li class="menu-item menu-item-sitemap">
          <a href="/sitemap.xml" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />
            
            站点地图
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/10/09/java-从源代码分析javaNIO的运行过程(一)/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="kyssion">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="kyssion-blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline"></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-10-09T15:22:37+08:00">
                2018-10-09
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="这一节解析一下-java-NIO中-ServerSocketChannel创建的过程"><a href="#这一节解析一下-java-NIO中-ServerSocketChannel创建的过程" class="headerlink" title="这一节解析一下 java NIO中 ServerSocketChannel创建的过程"></a>这一节解析一下 java NIO中 ServerSocketChannel创建的过程</h3><blockquote>
<p>channel  在java中表示通道，是用来进行数据的有效传输</p>
</blockquote>
<p>广义上来说通道可以被分为两类：<strong>File I/O和Stream I/O，也就是文件通道和套接字通道</strong></p>
<p>如果分的更细致一点则是：</p>
<ul>
<li>FileChannel 从文件读写数据</li>
<li>SocketChannel 通过TCP读写网络数据</li>
<li>ServerSocketChannel 可以监听新进来的TCP连接，并对每个链接创建对应的SocketChannel</li>
<li>DatagramChannel 通过UDP读写网络中的数据</li>
<li>Pipe</li>
</ul>
<p>通道既可以是单向的也可以是双向的。只实现ReadableByteChannel接口中的read()方法或者只实现WriteableByteChannel接口中的write()方法的通道皆为单向通道，同时实现ReadableByteChannel和WriteableByteChannel为双向通道，比如ByteChannel。对于socket通道来说，它们一直是双向的，而对于FileChannel来说，它同样实现了ByteChannel，但是我们知道<strong>通过FileInputStream的getChannel（）获取的FileChannel只具有文件的只读权限</strong>，那此时的在该通道调用write（）会出现什么情况？不出意外的抛出了NonWriteChannelException异常。<br>通过以上，我们得出结论：<strong>通道都与特定的I/O服务挂钩，并且通道的性能受限于所连接的I/O服务的性质。</strong></p>
<p>通道的工作模式有两种：阻塞或非阻塞。在非阻塞模式下，调用的线程不会休眠，请求的操作会立刻返回结果；在阻塞模式下，调用的线程会产生休眠。<strong>另外除FileChannel不能运行在非阻塞模式下，其余的通道都可阻塞运行也可以以非阻塞的方式运行。</strong></p>
<p>另外从SelectableChannel引申出的类可以和支持有条件选择的Selector结合使用，进而充分利用多路复用的I/O（multiplexed I/O）来提高性能.对于Socket通道类来说，通常与Selector共同使用以提高性能。需要<strong>注意的是通道不能被重复使用，一个打开的通道代表着与一个特定I/O服务进行连接并封装了该连接的状态，通道一旦关闭，该连接便会断开。</strong>通道的close（）比较特殊，无论在通道时在阻塞模式下还是非阻塞模式下，由于close（）方法的调用而导致底层I/O的关闭都可能会造成线程的暂时阻塞。在一个已关闭的通道上调用close（）并没有任何意义，只会立即返回。</p>
<h3 id="现在进入正题，讨论一下ServerSocketChannel"><a href="#现在进入正题，讨论一下ServerSocketChannel" class="headerlink" title="现在进入正题，讨论一下ServerSocketChannel"></a>现在进入正题，讨论一下ServerSocketChannel</h3><p>Java NIO中的 ServerSocketChannel 是一个可以监听新进来的TCP连接的通道, 类似ServerSocket一样。要注意的是和DatagramChannel和SocketChannel不同，ServerSocketChannel本身不具备传输数据的能力，而只是负责监听传入的连接和创建新的SocketChannel。</p>
<p><img src="/blogimg/nio/1.png" alt=""></p>
<h4 id="创建一个ServerSocket很简单，代码如下"><a href="#创建一个ServerSocket很简单，代码如下" class="headerlink" title="创建一个ServerSocket很简单，代码如下"></a>创建一个ServerSocket很简单，代码如下</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ServerSocketChannel channel= ServerSocketChannel.open();</span><br></pre></td></tr></table></figure>
<h4 id="深入研究一下，-进入ServerSocketChannel的open方法"><a href="#深入研究一下，-进入ServerSocketChannel的open方法" class="headerlink" title="深入研究一下， 进入ServerSocketChannel的open方法"></a>深入研究一下， 进入ServerSocketChannel的open方法</h4><blockquote>
<p>ServerSocketChannel类 open方法</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ServerSocketChannel <span class="title">open</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> SelectorProvider.provider().openServerSocketChannel();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里首先将会调用SelectorProvider的provider方法,这一局将会返回一个SelectorProvider实例,主要作用就是使用spi或者-Dxxx参数传入的SelectorProvider的类url地址（类的包名加类名）返回一个imp实例</p>
<blockquote>
<p>SelectorProvider类  provider() 方法</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> SelectorProvider <span class="title">provider</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">synchronized</span> (lock) &#123;</span><br><span class="line">        <span class="keyword">if</span> (provider != <span class="keyword">null</span>)</span><br><span class="line">           <span class="keyword">return</span> provider;</span><br><span class="line">        <span class="keyword">return</span> AccessController.doPrivileged(</span><br><span class="line">            <span class="keyword">new</span> PrivilegedAction&lt;SelectorProvider&gt;() &#123;</span><br><span class="line">                <span class="function"><span class="keyword">public</span> SelectorProvider <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                        <span class="keyword">if</span> (loadProviderFromProperty())</span><br><span class="line">                            <span class="keyword">return</span> provider;</span><br><span class="line">                        <span class="keyword">if</span> (loadProviderAsService())</span><br><span class="line">                            <span class="keyword">return</span> provider;</span><br><span class="line">                        provider = sun.nio.ch.DefaultSelectorProvider.create();</span><br><span class="line">                        <span class="keyword">return</span> provider;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>然后会调用实例的 openServerSocketChannel()方法</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> ServerSocketChannel <span class="title">openServerSocketChannel</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> ServerSocketChannelImpl(<span class="keyword">this</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这个方法将会真正的返回一个ServerSocketChannelImpl实例，这个类一般就是由虚拟机的厂商提供的，这里就不进行深入的研究了</p>
<h3 id="最后看一下这个serversocketchannel个人觉得有用的方法"><a href="#最后看一下这个serversocketchannel个人觉得有用的方法" class="headerlink" title="最后看一下这个serversocketchannel个人觉得有用的方法"></a>最后看一下这个serversocketchannel个人觉得有用的方法</h3><ol>
<li><strong>public static ServerSocketChannel open() throws IOException</strong> 开启一个serversocketchannel</li>
<li><strong>public final int validOps()</strong>：返回这个通道支持的SelectionKey值，应为这个通道只是开启一个SocketChannel并没有信息交换的功能，只是监听功能，所有只能返回SelectionKey.OP_ACCEPT</li>
<li><strong>public final ServerSocketChannel bind(SocketAddress local)和public final ServerSocketChannel bind(SocketAddress local，int backlog)</strong>：字如其意将一个套接字和本地地址链接，有一个重构方法提供最大链接数支持</li>
<li><strong>public ServerSocket socket()</strong>：返回一个ServerSocket </li>
<li><strong>public SocketChannel accept() throws IOException</strong>：和传统的网络编程相同，如果使用的Nio那么将会立即的返回null否则将会阻塞住直到有链接建立</li>
<li><strong>public SocketAddress getLocalAddress() throws IOException</strong>：返回这里绑定的地址</li>
<li><strong>public final SelectableChannel configureBlocking(boolean block) throws IOException</strong>: 指定这个接口是阻塞的还是非阻塞的</li>
</ol>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/10/09/spring5-condition注解实现bean细致控制/" rel="next" title="">
                <i class="fa fa-chevron-left"></i> 
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/10/09/java-一些基本知识点整理/" rel="prev" title="">
                 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">kyssion</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">133</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#这一节解析一下-java-NIO中-ServerSocketChannel创建的过程"><span class="nav-number">1.</span> <span class="nav-text">这一节解析一下 java NIO中 ServerSocketChannel创建的过程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#现在进入正题，讨论一下ServerSocketChannel"><span class="nav-number">2.</span> <span class="nav-text">现在进入正题，讨论一下ServerSocketChannel</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#创建一个ServerSocket很简单，代码如下"><span class="nav-number">2.1.</span> <span class="nav-text">创建一个ServerSocket很简单，代码如下</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#深入研究一下，-进入ServerSocketChannel的open方法"><span class="nav-number">2.2.</span> <span class="nav-text">深入研究一下， 进入ServerSocketChannel的open方法</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#最后看一下这个serversocketchannel个人觉得有用的方法"><span class="nav-number">3.</span> <span class="nav-text">最后看一下这个serversocketchannel个人觉得有用的方法</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">kyssion</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
